﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;

public static partial class Extensions
{
    /// <summary>
    /// 将json转为object
    /// </summary>
    public static T ToObject<T>(this string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }

    /// <summary>
    /// 将json转为type类型的object
    /// </summary>
    public static object ToObject(this string json, Type type)
    {
        return JsonConvert.DeserializeObject(json, type);
    }

    /// <summary>
    /// 将json转为List<T>
    /// </summary>
    public static List<T> ToList<T>(this string json)
    {
        return JsonConvert.DeserializeObject<List<T>>(json);
    }

    ///// <summary>
    ///// 将json转为type类型的List
    ///// </summary>
    //public static List<object> Json2List(string json, Type type)
    //{
    //    Type t = typeof(List<>).MakeGenericType(type);
    //    return (List<object>)JsonConvert.DeserializeObject(json, t);
    //}

    /// <summary>
    /// 将object转为json字符串
    /// </summary>
    public static string ToJson(this object obj, bool formated = false)
    {
        if (obj == null) return String.Empty;
        return JsonConvert.SerializeObject(obj, formated ? Formatting.Indented : Formatting.None);
    }
}